package com.botao.cms.poi;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.botao.cms.dao.UserMapper;
import com.botao.cms.pojo.User;
import com.botao.cms.utils.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 曹波涛
 */
@Controller
public class ExportUserInFo {
    @Autowired
    UserMapper userMapper;

    private XSSFWorkbook createWorkbook() {
        XSSFWorkbook workbook = new XSSFWorkbook();
        //工作表
        XSSFSheet sheet = workbook.createSheet("用户信息表");
        XSSFRow row = sheet.createRow(0);
        String[] title = {
                "姓名", "性别", "邮箱", "出生日期", "注册日期", "状态"
        };
        for (int i = 0; i < title.length; i++) {
            row.createCell(i).setCellValue(title[i]);
        }
        return workbook;
    }

    private void fillInFo(XSSFWorkbook workbook) {
        List<User> userList = userMapper.selectList(new QueryWrapper<User>().orderByDesc("state"));





        AtomicInteger i = new AtomicInteger();
        userList.forEach(user -> {
            i.getAndIncrement();
            XSSFSheet sheet = workbook.getSheet("用户信息表");
            XSSFRow row = sheet.createRow(i.get());
            row.createCell(0).setCellValue(user.getUsername());
            row.createCell(1).setCellValue(user.getSex());
            row.createCell(2).setCellValue(user.getEmail());
            row.createCell(3).setCellValue(DateUtil.format(user.getBirthday()));
            row.createCell(4).setCellValue(DateUtil.format(user.getCreated()));
            Integer state = user.getState();
            if (state == 0) {
                row.createCell(5).setCellValue("停用");
            } else if (state == 1) {
                row.createCell(5).setCellValue("用户");
            } else {
                row.createCell(5).setCellValue("管理");
            }
        });
    }

    public void export(HttpServletResponse response) throws IOException {
        XSSFWorkbook workbook = createWorkbook();
        fillInFo(workbook);
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/octet-stream;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + "userInFo.xlsx");
        workbook.write(outputStream);
        workbook.close();
        outputStream.flush();
        outputStream.close();
    }
}
